package com.ruoyi.baseMain.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.approval.v4.model.CreateInstanceReq;
import com.lark.oapi.service.approval.v4.model.CreateInstanceResp;
import com.lark.oapi.service.approval.v4.model.InstanceCreate;
import com.ruoyi.GetToken;
import com.ruoyi.baseMain.domain.bo.BasePolicyHisBo;
import com.ruoyi.baseMain.domain.vo.BasePolicyHisVo;
import com.ruoyi.baseMain.service.IBasePolicyHisService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.baseMain.domain.vo.BasePolicyVo;
import com.ruoyi.baseMain.domain.bo.BasePolicyBo;
import com.ruoyi.baseMain.service.IBasePolicyService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 客户政策
 *
 * @author linziheng
 * @date 2024-01-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/baseMain/policy")
public class BasePolicyController extends BaseController {

    private final IBasePolicyService iBasePolicyService;
    private final IBasePolicyHisService iBasePolicyHisService;
    private final ISysUserService userService;
    private final ISysDeptService sysDeptService;
    /**
     * 查询客户政策列表
     */
    @SaCheckPermission("baseMain:policy:list")
    @GetMapping("/list")
    public TableDataInfo<BasePolicyVo> list(BasePolicyBo bo, PageQuery pageQuery) {
        TableDataInfo<BasePolicyVo> list =  iBasePolicyService.queryPageList(bo, pageQuery);
        return list;
    }
    /**
     * 查询客户媒介对应数据
     */
    @SaCheckPermission("baseMain:policy:list")
    @GetMapping("/mediumList")
    public TableDataInfo<BasePolicyVo> mediumList(BasePolicyBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getUserId());
        for (SysRole role : user.getRoles()) {
            List<Long> list = new ArrayList<>();
            list.add(1L);
            list.add(1719534201567039490L);
            list.add(1744703082709377025L);
            if(!list.contains(role.getRoleId())){
                bo.setOperateUserName(user.getNickName());
            }
        }
        return iBasePolicyService.queryPageList(bo, pageQuery);
    }


    @GetMapping("/getListNoPages")
    public List<BasePolicyVo> getListNoPages(BasePolicyBo bo) {
        List<BasePolicyVo> list = iBasePolicyService.queryList(bo);
        return list;
    }
    /**
     * 导出客户政策列表
     */
    @SaCheckPermission("baseMain:policy:export")
    @Log(title = "客户政策", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BasePolicyBo bo, HttpServletResponse response) {
        List<BasePolicyVo> list = iBasePolicyService.queryList(bo);
        ExcelUtil.exportExcel(list, "客户政策", BasePolicyVo.class, response);
    }

    /**
     * 获取客户政策详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("baseMain:policy:query")
    @GetMapping("/{id}")
    public R<BasePolicyVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iBasePolicyService.queryById(id));
    }
    @GetMapping("/approve/{id}")
    public R<BasePolicyVo> approve(@NotNull(message = "主键不能为空")
                                   @PathVariable Long id) {
        // 更新政策表 数据及状态
        //查询历史表最新一条记录
        BasePolicyHisBo basePolicyHisBo = new BasePolicyHisBo();
        basePolicyHisBo.setPolicyId(id);

        List<BasePolicyHisVo> list = iBasePolicyHisService.queryList(basePolicyHisBo);
        if(list.size()>0){
            if(list.get(0).getStatus().equals("2")){
                //更新数据
                BasePolicyBo basePolicyBo = BeanUtil.toBean(list.get(0), BasePolicyBo.class);
                BasePolicyHisBo hbo = BeanUtil.toBean(list.get(0), BasePolicyHisBo.class);
                basePolicyBo.setId(list.get(0).getPolicyId());
                basePolicyBo.setStatus("1");
                iBasePolicyService.updateByBo(basePolicyBo);
                hbo.setStatus("1");
                hbo.setApproveUser(LoginHelper.getUserId().toString());
                hbo.setApproveUserName(LoginHelper.getNickName());
                iBasePolicyHisService.updateByBo(hbo);
            }
        }
        return R.ok();
    }
    @GetMapping("/reject/{id}")
    public R<BasePolicyVo> reject(@NotNull(message = "主键不能为空")
                                   @PathVariable Long id) {
        // 更新政策表 数据及状态
            //查询历史表最新一条记录
        BasePolicyHisBo basePolicyHisBo = new BasePolicyHisBo();
        basePolicyHisBo.setPolicyId(id);

        List<BasePolicyHisVo> list = iBasePolicyHisService.queryList(basePolicyHisBo);
        if(list.size()>0){
            if(list.get(0).getStatus().equals("2")){
                //更新数据
                BasePolicyBo basePolicyBo = BeanUtil.toBean(list.get(0), BasePolicyBo.class);
                BasePolicyHisBo hbo = BeanUtil.toBean(list.get(0), BasePolicyHisBo.class);
                basePolicyBo.setId(list.get(0).getPolicyId());
                basePolicyBo.setStatus("3");
                iBasePolicyService.updateByBo(basePolicyBo);
                hbo.setStatus("3");
                hbo.setApproveUser(LoginHelper.getUserId().toString());
                hbo.setApproveUserName(LoginHelper.getNickName());
                iBasePolicyHisService.updateByBo(hbo);
            }
        }
        return R.ok();
    }

    /**
     * 新增客户政策
     */
    @SaCheckPermission("baseMain:policy:add")
    @Log(title = "客户政策", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BasePolicyBo bo) throws Exception {
        //新增数据未审批数据
        bo.setStatus("2");
        LoginUser LoginUser = LoginHelper.getLoginUser();
        bo.setOperateUserName(LoginHelper.getLoginUser().getNickName());
        bo.setBusinessUnitName(LoginHelper.getLoginUser().getDeptName());
       // SysDept ysDept = sysDeptService.selectDeptById(LoginHelper.getLoginUser().getDeptId());
        R r = instancesCreate(bo,"AE0B419F-4626-4C25-AB4B-3307077D872B");
        Boolean flag = false;
        if(r.getCode() == 200){
             bo.setInstanceCode(r.getMsg());
             flag = iBasePolicyService.insertByBo(bo);
             iBasePolicyService.updateByBo(bo);

             BasePolicyHisBo basePolicyHisBo = BeanUtil.toBean(bo, BasePolicyHisBo.class);
             basePolicyHisBo.setId(null);
             basePolicyHisBo.setStatus("2");
             basePolicyHisBo.setPolicyId(bo.getId());
             iBasePolicyHisService.insertByBo(basePolicyHisBo);
         }



        return toAjax(flag);
    }

    public R instancesCreate(BasePolicyBo bo,String inten) throws Exception {
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();

        JSONArray ja = new JSONArray();
        JSONObject jb1 = new JSONObject();
        jb1.set("id","nickName");
        jb1.set("type","input");
        jb1.set("value",bo.getNickName());
        ja.add(jb1);

        JSONObject jb2 = new JSONObject();
        jb2.set("id","accountPoint");
        jb2.set("type","number");
        jb2.set("value",bo.getAccountPoint());
        ja.add(jb2);

        JSONObject jb3 = new JSONObject();
        jb3.set("id","privatePoint");
        jb3.set("type","number");
        jb3.set("value",bo.getPrivatePoint());
        ja.add(jb3);

        JSONObject jb4 = new JSONObject();
        jb4.set("id","signatory");
        jb4.set("type","input");
        jb4.set("value",bo.getSignatory());
        ja.add(jb4);

        JSONObject jb5 = new JSONObject();
        jb5.set("id","policyType");
        jb5.set("type","input");
        jb5.set("value",bo.getPolicyType());
        ja.add(jb5);

        JSONObject jb6 = new JSONObject();
        jb6.set("id","totalPoint");
        jb6.set("type","input");
        jb6.set("value",bo.getTotalPoint().toString());
        ja.add(jb6);

        JSONObject jb7 = new JSONObject();
        jb7.set("id","policyTag");
        jb7.set("type","input");
        jb7.set("value",bo.getPolicyTag());
        ja.add(jb7);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(bo.getTakeTime());

        JSONObject jb8 = new JSONObject();
        jb8.set("id","takeTime");
        jb8.set("type","input");
        jb8.set("value",dateString);
        ja.add(jb8);


        JSONObject jb9 = new JSONObject();
        jb9.set("id","aparty");
        jb9.set("type","input");
        jb9.set("value",bo.getAparty());
        ja.add(jb9);

        JSONObject jb10= new JSONObject();
        jb10.set("id","channel");
        jb10.set("type","input");
        jb10.set("value",bo.getChannel());
        ja.add(jb10);

        JSONObject jb11 = new JSONObject();
        jb11.set("id","cooperateType");
        jb11.set("type","input");
        jb11.set("value",bo.getCooperateType());
        ja.add(jb11);

        JSONObject jb12 = new JSONObject();
        jb12.set("id","payType");
        jb12.set("type","input");
        jb12.set("value",bo.getPayType());
        ja.add(jb12);

        JSONObject jb13 = new JSONObject();
        jb13.set("id","bparty");
        jb13.set("type","input");
        jb13.set("value",bo.getBparty());
        ja.add(jb13);


        String from = ja.toString();
        // 创建请求对象
        String openId = LoginHelper.getLoginUser().getFeishuId();
        CreateInstanceReq req = CreateInstanceReq.newBuilder()
            .instanceCreate(InstanceCreate.newBuilder()
                .approvalCode(inten)
                .openId(openId)
                .form(from)
                .build())
            .build();

        // 发起请求
        CreateInstanceResp resp = client.approval().v4().instance().create(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s"
                , resp.getCode(), resp.getMsg(), resp.getRequestId()));
            return R.fail();
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));

        return R.ok(resp.getData().getInstanceCode());
    }

    /**
     * 修改客户政策
     */
    @SaCheckPermission("baseMain:policy:edit")
    @Log(title = "客户政策", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BasePolicyBo bo) throws Exception {
        BasePolicyVo basePolicyVo =  iBasePolicyService.queryById(bo.getId());
        if(basePolicyVo.getStatus().equals("2")){
            return R.warn("数据审批中，请勿修改！");
        }
        //新增数据未审批数据
        bo.setStatus("2");
        Boolean flag = false;
        R r = instancesCreate(bo,"8400D9BF-5A9A-489A-A003-3EDFC1AC60B4");
        if(r.getCode() == 200) {
            bo.setInstanceCode(r.getMsg());

            iBasePolicyService.updateByBo(bo);

            BasePolicyHisBo basePolicyHisBo = BeanUtil.toBean(bo, BasePolicyHisBo.class);
            basePolicyHisBo.setId(null);
            basePolicyHisBo.setStatus("2");
            basePolicyHisBo.setPolicyId(bo.getId());
            flag = iBasePolicyHisService.insertByBo(basePolicyHisBo);
        }
        return toAjax(flag);
    }

    /**
     * 删除客户政策
     *
     * @param ids 主键串
     */
    @SaCheckPermission("baseMain:policy:remove")
    @Log(title = "客户政策", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iBasePolicyService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
